package leetcode.leetcode_hot100;

import java.util.LinkedList;

/**
 * @ClassName T0394
 * @Description 字符串解码
 * @Author Fanxc
 * @DATE 2021/6/19 9:53
 * @Version 1.0
 */
public class T0394 {
    //肯定需要两个栈，一个用来存数字，另一个存字符串
    //需要对[]进行判断
    class Solution {
        public String decodeString(String s) {
            LinkedList<Integer> stk_multi = new LinkedList<>();//用来存数字
            LinkedList<String> stk_res = new LinkedList<>();//用来存字母
            StringBuilder res = new StringBuilder();
            int multi = 0;
            for (Character c : s.toCharArray()) {
                if (c == '[') {
                    //把[前面的数字和字符串入栈
                    stk_multi.addLast(multi);
                    stk_res.addLast(res.toString());
                    multi = 0;
                    res = new StringBuilder();
                } else if (c == ']') {
                    //把]到[之间的字符串合并后重新入栈
                    int cur = stk_multi.removeLast();
                    StringBuilder tmp = new StringBuilder();
                    for (int i = 0; i < cur; i++) {
                        tmp.append(res);
                    }
                    res = new StringBuilder(stk_res.removeLast() + tmp);
                } else if (c >= '0' && c <= '9') {
                    multi = multi * 10 + (c - '0');//字符串可能超过10
                } else {
                    res.append(c);//字符集合为字符串
                }
            }
            return res.toString();
        }
    }
}
